/**
	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package br.biofoco.p2p.services;

import java.io.IOException;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.google.inject.Inject;


public class ServiceCatalogue {

	private final ConcurrentMap<Long, Service<?>> serviceMap = new ConcurrentHashMap<Long,Service<?>>();
	private ServiceLoader loader;
	
	@Inject
	public ServiceCatalogue(ServiceLoader loader) {
		this.loader = loader;
		load();
	}
	
	public void load() {
		try {
			addServices(loader.loadServices());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void addServices(Collection<? extends Service<?>> services) {
		for (Service<?> service : services){
			addService(service);
		}
	}
	
	public void addService(Service<?> service){
		serviceMap.putIfAbsent(service.getId(), service);
	}
	
	public Service<?> get(Long id){
		return serviceMap.get(id);
	}
	
	public String toString() {
		StringBuilder builder = new StringBuilder();
		for (Entry<Long, Service<?>> entry : serviceMap.entrySet()){
			builder.append("[" + entry.getKey())
				   .append("-->")
				   .append(entry.getValue() + "]")
				   .append("\n");
		}
		return builder.toString();
	}

	public Collection<Service<?>> listServices() {
		return serviceMap.values();
	}
}
